/*
 * NewDownloadFrame.java
 *
 * Created on __DATE__, __TIME__
 */

package Windows.DownLoads;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import Tools.IMG;
import Tools.JLabelStyle;
import Tools.Log;
import Tools.ToCenter;
import Tools.Units;
import Windows.MainWindows;
import Windows.PicPanel;
import Windows.ShowWindows.ShowWindow;
import XML.XMLNode;

import com.sunking.swing.JDirChooser;

/**
 * 
 * @author __USER__
 */
public class NewDownloadFrame extends javax.swing.JFrame implements DocumentListener, ActionListener {
	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			@Override
			public void run() {
				XMLNode xf = new XMLNode(null, "File");
				xf.put("name", "qq2009.exe");
				xf.put("md5", "ASDF66FDS6F56SDFSDFDS");
				NewDownloadFrame n = new NewDownloadFrame(null);
				n.setVisible(true);
			}
		});
	}
	private XMLNode xf;

	private ShowDownloadPanel sdp;

	// GEN-BEGIN:variables
	// Variables declaration - do not modify
	public javax.swing.JButton jBDownload;

	private javax.swing.JButton jButton1;

	private javax.swing.JLabel jLabel1;

	private javax.swing.JLabel jLabel2;

	private javax.swing.JLabel jLabel3;

	private javax.swing.JLabel jLabel4;

	public javax.swing.JPanel jPanel2;

	private javax.swing.JLabel jlbDisk;

	private javax.swing.JPanel jpTop;

	public javax.swing.JTextField jtfFileName;
	private javax.swing.JTextField jtfMd5;
	public javax.swing.JTextField jtfSave;
	/** Creates new form NewDownloadFrame */
	public NewDownloadFrame(ShowDownloadPanel sdp) {
		super("新建下载任务");
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		this.sdp = sdp;
		xf = new XMLNode(null, "");

		setContentPane(new PicPanel(IMG.DOWNBG));

		jPanel2 = new PicPanel(IMG.blank, IMG.DOWNLOADBG);
		jpTop = new PicPanel(IMG.banner);
		initComponents();

		this.jBDownload.setActionCommand("立即下载");
		jtfFileName.getDocument().addDocumentListener(this);
		// jtfMd5.getDocument().addDocumentListener(this);
		// System.out.println("注册鼠标事件,");

		jtfSave.getDocument().addDocumentListener(this);
		this.setResizable(false);
		MouseListener ml = ((PicPanel) jPanel2).getMouseListener();
		jLabel1.addMouseListener(ml);
		jLabel2.addMouseListener(ml);
		jLabel3.addMouseListener(ml);
		jtfFileName.addMouseListener(ml);
		jtfSave.addMouseListener(ml);
		jtfMd5.addMouseListener(ml);
		jButton1.addMouseListener(ml);

		this.jlbDisk.addMouseListener(JLabelStyle.getStyleListener());
		// System.out.println("注册鼠标事件.");
		jBDownload.addActionListener(this);
		this.addWindowListener(ShowWindow.getWindowListener());
	}
	// End of variables declaration//GEN-END:variables
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		Object obj = e.getSource();
		if (obj.getClass() == JButton.class) {
			JButton jb = (JButton) obj;
			if (jb.getActionCommand().equals("立即下载")) {

				sdp.addFile(getXf());// 向下载面板中新建一个任务，并启动
				setVisible(false);

			}
		}
	}
	@Override
	public void changedUpdate(DocumentEvent arg0) {
		// TODO Auto-generated method stub
//		UpdateDiskStateLable();
	}
	public XMLNode getXf() {
		return xf;
	}
	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jLabel1 = new javax.swing.JLabel();
		jtfMd5 = new javax.swing.JTextField();
		jLabel2 = new javax.swing.JLabel();
		jtfSave = new javax.swing.JTextField();
		jButton1 = new javax.swing.JButton();
		jLabel3 = new javax.swing.JLabel();
		jtfFileName = new javax.swing.JTextField();
		jLabel4 = new javax.swing.JLabel();
		jBDownload = new javax.swing.JButton();
		jlbDisk = new javax.swing.JLabel();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

		org.jdesktop.layout.GroupLayout jpTopLayout = new org.jdesktop.layout.GroupLayout(jpTop);
		jpTop.setLayout(jpTopLayout);
		jpTopLayout.setHorizontalGroup(jpTopLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(0, 478, Short.MAX_VALUE));
		jpTopLayout.setVerticalGroup(jpTopLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(0, 77, Short.MAX_VALUE));

		jPanel2.setBackground(new java.awt.Color(204, 240, 255));
		jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

		jLabel1.setText("\u6587\u4ef6\u5730\u5740");

		jLabel2.setText("\u4fdd\u5b58\u4f4d\u7f6e");

		jButton1.setText("...");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			@Override
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});

		jLabel3.setText("\u6587\u4ef6\u540d");

		org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
		jPanel2.setLayout(jPanel2Layout);
		jPanel2Layout
				.setHorizontalGroup(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
						jPanel2Layout
								.createSequentialGroup()
								.add(24, 24, 24)
								.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false).add(jPanel2Layout.createSequentialGroup().add(jLabel1).add(18, 18, 18).add(jtfMd5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 263, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
										.add(jPanel2Layout.createSequentialGroup().add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING).add(jLabel3).add(jLabel2)).add(18, 18, 18).add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jPanel2Layout.createSequentialGroup().add(jtfFileName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 164, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(jLabel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)).add(jtfSave)))).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 30, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
								.addContainerGap(53, Short.MAX_VALUE)));
		jPanel2Layout.setVerticalGroup(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(
				jPanel2Layout.createSequentialGroup().addContainerGap().add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(jLabel1).add(jtfMd5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)).addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED).add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(jLabel2).add(jtfSave, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(jButton1)).addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
						.add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(jLabel3).add(jtfFileName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(jLabel4)).addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

		jBDownload.setText("\u7acb\u5373\u4e0b\u8f7d");

		jlbDisk.setText("jLabel4");

		org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jpTop, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(layout.createSequentialGroup().add(10, 10, 10).add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addContainerGap()).add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup().addContainerGap().add(jlbDisk, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 367, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED).add(jBDownload).addContainerGap()));
		layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(layout.createSequentialGroup().add(jpTop, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(18, 18, 18).add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED).add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(jBDownload).add(jlbDisk)).addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));

		pack();
	}// </editor-fold>
		// GEN-END:initComponents
	@Override
	public void insertUpdate(DocumentEvent arg0) {
		UpdateDiskStateLable();
	}
	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
		File f = JDirChooser.showDialog(this, "请选择保存位置", true, null, "请选择");
		if (f != null) {
			jtfSave.setText(f.getAbsolutePath());
		}

	}
	@Override
	public void removeUpdate(DocumentEvent arg0) {
		UpdateDiskStateLable();
	}
	/**
	 * 新建任务
	 * 
	 * @param task
	 */
	public void setNewTask(XMLNode task, boolean amend) {
		String flag = task.toString();
		XMLNode xn = XML.XML.parseFlag(flag.substring(1, flag.length() - 1));

		String md5 = xn.get("md5");
		String name = xn.get("name");

		xf = xn;

		Log.print("[准备下载]" + xf);

		// 注意：由于文本域注册了文本更新监听器，修改其中一个文本域中的的文本后，xf中的所有相关属性会自动更新。

		jtfMd5.setText(md5);
		jtfFileName.setText(name);
		jtfMd5.setEnabled(amend);

		if (jtfSave.getText().length() == 0) {
			jtfSave.setText(MainWindows.getInstance().client.sp.getF().getAbsolutePath());
		}

		ToCenter.ToCenter(this);
		ShowWindow.DisplayWindow(this, 1);
	}

	public void UpdateDiskStateLable() {
		long size = 0;
		try {
			size = Long.parseLong(xf.get("size"));
		} catch (Exception e) {
		}
		File f = new File(jtfSave.getText());
		size = f.getFreeSpace() - size;
		size = size < 0 ? 0 : size;
		double dl = f.getTotalSpace() > 0 ? (double) Units.byteCondensInt(f.getFreeSpace()) / Units.byteCondensInt(f.getTotalSpace()) : 1.0d;

		jBDownload.setEnabled(size > 1024);
		if (dl < 0.1) {
			jlbDisk.setForeground(Color.RED);
		} else if (dl < 0.3) {
			jlbDisk.setForeground(Color.ORANGE);
		} else {
			jlbDisk.setForeground(Color.BLUE);
		}

		jlbDisk.setText("剩余空间:" + Units.byteCondense(size) + "　　　　磁盘空间:" + Units.byteCondense(f.getTotalSpace()));

		// --刷新xmlFlag数据

		String FilePath = jtfSave.getText();
		FilePath = FilePath.replaceAll("\\+", "\\");
		FilePath = FilePath.replaceAll("/+", "\\");
		FilePath = (!(FilePath.endsWith("\\") || FilePath.endsWith("/")) ? FilePath + "\\" : FilePath) + jtfFileName.getText();
		if (jtfMd5.getText().length() >= 16)
			xf.put("md5", jtfMd5.getText());
		xf.put("filepath", FilePath);
		xf.put("name", jtfFileName.getText());

		File file = new File(getXf().get("filepath"));
		boolean mpty = jtfFileName.getText().length() == 0;
		jLabel4.setText(mpty ? "请输入文件名" : file.exists() ? "文件名已存在！" : "");
		jLabel4.setForeground(file.exists() || mpty ? Color.RED : Color.BLUE);
		jBDownload.setVisible(!file.exists());
	}
}